<?php

class Debug implements ISingleton
{
	/**
	 * @var Debug
	 */
	protected static $_instance;

	/**
	 * @var boolean
	 */
	private $_debugMode = false;

	/**
	 * Disallow cloning
	 */
	private function __clone() {
		throw new Exception('Clone is not allowed.');
	}

	/**
	 * Protected constructor, cannot be called directly, initialize
	 * only via getInstance().
	 */
	protected function __construct()
	{
		$config = Config::getInstance();
		// Get debug mode settings from ini file
		$this->_debugMode = $config->debug->mode;
		// Try to enable debug mode via HTTP authorization
		if (!$this->isDebugMode()) {
			// Valid user login:password
			$user = preg_split('/:/', $config->debug->user, null, PREG_SPLIT_NO_EMPTY);
			// Validate user
			$validUser = count($user) == 2 && @$_SERVER['PHP_AUTH_USER'] == $user[0] && @$_SERVER['PHP_AUTH_PW'] == $user[1];
			if ($validUser || (isset($_GET['debug']) && !$config->debug->requireAuth)) {
				$this->_debugMode = true;
			} elseif (!headers_sent() && key_exists('debug', $_GET) && ($_GET['debug'] || $_GET['debug'] === null)) {
				header('WWW-Authenticate: Basic realm="Debug mode"');
				header('HTTP/1.0 401 Unauthorized');
				// @todo make sexy error message (maybe ZF MVC view)
				die("Not authorized");
			}
		} elseif (isset($_GET['debug']) && !$_GET['debug']) {
			// Switch off debug mode
			$this->_debugMode = false;
		}
	}

	/**
	 * Return Debug object instance
	 *
	 * @return Debug
	 */
	public static function getInstance()
	{
		if (!self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Is debug mode enabled
	 *
	 * @return boolean
	 */
	public function isDebugMode()
	{
		return $this->_debugMode;
	}
	
	public function hideDebug(){
		Zend_Controller_Front::getInstance()->unregisterPlugin("Debug_ControllerPlugin");
	}

	/**
	 * Wrap for function exit(). Show debug backtrace before.
	 * NOT FOR USE. JUST FOR REPLACE OLD EXITS.
	 *
	 * @param string $message
	 * @return void
	 */
	public function shutdown()
	{
		if (!$this->isDebugMode()) {
			try {
				throw new Exception('Debug shutdown');
			} catch (Exception $e) {
				require_once 'ErrorLowlevel.php';
			}
		} else {
			$debug = '<h1>Process unpredictably stopped.</h1>';
			echo '<pre>';
			$args = func_get_args();
			foreach ($args as $arg) {
				var_dump($arg);
			}
			echo '</pre>';

			$backtrace = debug_backtrace();
			$stacks = Debug_TraceHelper::getStacktrace($backtrace);
			foreach ($stacks as $stack) {
				$debug .= "<p>$stack</p>";
			}

			echo $debug;
		}

		exit;
	}
	

}